package com.caiden_micheal.base.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    private static StringRedisTemplate stringRedisTemplate;

    @Resource
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        RedisUtil.stringRedisTemplate = stringRedisTemplate;
    }

    // 设置键值对
    public static void setKey(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    // 获取键对应的值
    public static String getValue(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    // 删除键
    public static void deleteKey(String key) {
        stringRedisTemplate.delete(key);
    }

    public static void deleteFold(String pattern) {
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setScriptText("local keys = redis.call('keys', ARGV[1]) for i = 1, #keys, 5000 do redis.call('del', unpack(keys, i, math.min(i+4999, #keys))) end return #keys");
        script.setResultType(Long.class);
        stringRedisTemplate.execute(script, Collections.emptyList(), pattern);
    }

    // 设置键的过期时间
    public static void expireKey(String key, long timeout) {
        stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
    }

    // 判断键是否存在
    public static boolean hasKey(String key) {
        return Boolean.TRUE.equals(stringRedisTemplate.hasKey(key));
    }

    // 自增操作
    public static Long increment(String key, long delta) {
        return stringRedisTemplate.opsForValue().increment(key, delta);
    }

    // 自减操作
    public static Long decrement(String key, long delta) {
        return stringRedisTemplate.opsForValue().increment(key, -delta);
    }
}